#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/10 17:56
# @Author  : harry
import threading

import requests
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from wechatpy import WeChatClient
from dvadmin.utils.json_response import DetailResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin_wechat.models import FanGroups, OfficialAccountManagement
from dvadmin_wechat.tools import sync_groups


def get_access_token(data):
    res = requests.get(
        url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
            data.appid, data.app_secret))
    if "access_token" in res.text:
        return res.json().get('access_token')

    else:
        return False


class FanGroupsCreateSerializer(CustomModelSerializer):
    class Meta:
        model = FanGroups
        fields = "__all__"
        read_only_fields = ["id"]

    def validate(self, attrs):
        request = self.context.get("request")
        official_account_management_id = request.data.get("official_account_management_id")
        name = request.data.get("name")
        if not official_account_management_id:
            raise serializers.ValidationError('公众号id必传')
        if not name:
            raise serializers.ValidationError("组名必传")
        o_a_m = OfficialAccountManagement.objects.filter(id=official_account_management_id).first()
        if not o_a_m:
            raise serializers.ValidationError("请输入正确的公众号")
        access_token = get_access_token(o_a_m)
        if access_token:
            client = WeChatClient(o_a_m.appid, o_a_m.app_secret)
            res = client.group.create(name)
            # print(res, "<<<<<<res<")
            if "errcode" not in res:
                attrs['groupid'] = res.get('group').get("id")
                attrs['name'] = name
                attrs['official_account_management_id'] = official_account_management_id
            else:
                raise serializers.ValidationError("请输入正确的信息")
        else:
            raise serializers.ValidationError("请输入正确的信息")
        return attrs


class FanGroupsViewSet(CustomModelViewSet):
    """
    菜单管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = FanGroups.objects.filter(official_account_management__status=1)
    serializer_class = FanGroupsCreateSerializer
    create_serializer_class = FanGroupsCreateSerializer
    update_serializer_class = FanGroupsCreateSerializer
    search_fields = ['name', ]
    filter_fields = ['name', 'official_account_management_id']

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def sync(self, request):
        """同步组信息"""
        official_account_management = self.request.query_params.get('official_account_management_id')
        for th in threading.enumerate():
            if th.name == "sync_group_111":
                return ErrorResponse(msg="上一次同步组还未完成,请稍后再试")
        t = threading.Thread(name='sync_group_111', target=sync_groups,
                             kwargs={'official_account_management': official_account_management})
        t.daemon = True
        t.start()
        return DetailResponse(data=None, msg="同步成功")

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        client = WeChatClient(instance.official_account_management.appid,
                              instance.official_account_management.app_secret)
        res = client.group.delete(instance.groupid)
        instance.delete()
        return DetailResponse(data=[], msg="删除成功")
